import store from '@/store/index'
import {handleCode} from "@/api/index";

export function hxHandler(data) {

    switch (data.command){
        case 'initApp':
            store.commit('app/setApiKey',data.data.apiKey)
            store.commit('app/setBaseUrl',data.data.baseUrl)
            store.commit('app/setThemeInfo',data.data.themeInfo)
            store.commit('app/setActiveModel',data.data.modelName)
            localStorage.setItem('baseConfig',JSON.stringify(data.data))
            break;
        case 'updateToken':
            store.commit('app/setToken', data.data);
            break;
        case  'updateTheme':
            store.commit('app/setThemeInfo', data.data)
            break;
        case  'updateApiKey':
            store.commit('app/setApiKey', data.data)
            break;
        case  'updateBaseUrl':
            store.commit('app/setBaseUrl', data.data)
            break;
        case  'updateModelName':
            store.commit('app/setActiveModel', data.data)
            break;
        case  'explainCode':
            handleCode(data.data, '帮我解释这段代码')
            break;
        case  'optimizeCode':
            handleCode(data.data, '帮我优化这段代码')
            break;
        case  'commentCode':
            handleCode(data.data, '帮我为这段代码添加注释')
            break;
        case  'projectInfo':
            store.commit('app/setProjectInfo', data.data)
            break;
        default:
            break;
    }
}

export function postMessage(data) {
    window.hbuilderx.postMessage({
      command: data.command,
      data: data.data
    });
}

export function onHxMessage(){
    window.addEventListener("hbuilderxReady", ()=>{
        try {
            window.hbuilderx.onDidReceiveMessage((msg) => {
                hxHandler(msg)
            });
        } catch (error) {
            console.log(error);
            alert(error)
        }
    });

}
function onMessage(data){
    console.log(data)
}